<template>
  <el-card>
    <h2>结算管理</h2>
    <el-button type="primary" @click="openAdd">新增结算</el-button>
    <el-table :data="settlements" style="width: 100%;margin-top:16px">
      <el-table-column prop="settlementId" label="ID" width="60" />
      <el-table-column label="入住记录">
        <template #default="scope">
          {{ getCheckInInfo(scope.row.checkInId) }}
        </template>
      </el-table-column>
      <el-table-column prop="checkInDays" label="入住天数" width="100" />
      <el-table-column prop="roomFee" label="房费" width="100" />
      <el-table-column prop="consumptionFee" label="消费费" width="90" />
      <el-table-column prop="discount" label="折扣" width="90" />
      <el-table-column prop="totalFee" label="总费用" width="100" />
      <el-table-column prop="deposit" label="押金" width="100" />
      <el-table-column prop="refundAmount" label="退款金额" width="100" />
      <el-table-column prop="paymentMethod" label="支付方式" width="100" />
      <el-table-column label="结算时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.settlementDate) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="onDelete(scope.row.settlementId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="入住记录" prop="checkInId">
          <el-select v-model="form.checkInId" placeholder="请选择入住记录" style="width: 100%">
            <el-option 
              v-for="checkIn in activeCheckIns" 
              :key="checkIn.checkInId" 
              :label="`${getCustomerName(checkIn.customerId)} - ${getRoomNumber(checkIn.roomId)}`" 
              :value="checkIn.checkInId" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入住天数" prop="checkInDays">
          <el-input v-model="form.checkInDays" type="number" placeholder="请输入入住天数" />
        </el-form-item>
        <el-form-item label="房费" prop="roomFee">
          <el-input v-model="form.roomFee" type="number" placeholder="请输入房费" />
        </el-form-item>
        <el-form-item label="消费费" prop="consumptionFee">
          <el-input v-model="form.consumptionFee" type="number" placeholder="请输入消费费" />
        </el-form-item>
        <el-form-item label="折扣" prop="discount">
          <el-input v-model="form.discount" type="number" placeholder="请输入折扣金额" />
        </el-form-item>
        <el-form-item label="总费用" prop="totalFee">
          <el-input v-model="form.totalFee" type="number" placeholder="请输入总费用" />
        </el-form-item>
        <el-form-item label="押金" prop="deposit">
          <el-input v-model="form.deposit" type="number" placeholder="请输入押金" />
        </el-form-item>
        <el-form-item label="退款金额" prop="refundAmount">
          <el-input v-model="form.refundAmount" type="number" placeholder="请输入退款金额" />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="form.paymentMethod" placeholder="请选择支付方式">
            <el-option label="现金" value="cash" />
            <el-option label="信用卡" value="credit_card" />
            <el-option label="借记卡" value="debit_card" />
            <el-option label="移动支付" value="mobile_payment" />
          </el-select>
        </el-form-item>
        <el-form-item label="结算时间" prop="settlementDate">
          <el-date-picker 
            v-model="form.settlementDate" 
            type="datetime" 
            placeholder="选择结算时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="form.notes" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { getSettlements, addSettlement, updateSettlement, deleteSettlement } from '../api/settlement';
import { getCheckIns } from '../api/checkIn';
import { getCustomers } from '../api/customer';
import { getRooms } from '../api/room';
import { ElMessage, ElMessageBox } from 'element-plus';

const settlements = ref([]);
const checkIns = ref([]);
const customers = ref([]);
const rooms = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref('');
const form = ref({ 
  settlementId: null, 
  checkInId: '', 
  userId: 1, // 默认操作员ID
  checkInDays: '', 
  roomFee: '', 
  consumptionFee: 0, 
  discount: 0, 
  totalFee: '', 
  deposit: '', 
  refundAmount: '', 
  paymentMethod: '', 
  settlementDate: '', 
  notes: '' 
});
const formRef = ref();

const rules = {
  checkInId: [{ required: true, message: '请选择入住记录', trigger: 'change' }],
  checkInDays: [{ required: true, message: '请输入入住天数', trigger: 'blur' }],
  roomFee: [{ required: true, message: '请输入房费', trigger: 'blur' }],
  totalFee: [{ required: true, message: '请输入总费用', trigger: 'blur' }],
  deposit: [{ required: true, message: '请输入押金', trigger: 'blur' }],
  paymentMethod: [{ required: true, message: '请选择支付方式', trigger: 'change' }],
  settlementDate: [{ required: true, message: '请选择结算时间', trigger: 'change' }]
};

const loadSettlements = async () => {
  settlements.value = await getSettlements();
};

const loadCheckIns = async () => {
  checkIns.value = await getCheckIns();
};

const loadCustomers = async () => {
  customers.value = await getCustomers();
};

const loadRooms = async () => {
  rooms.value = await getRooms();
};

const getCheckInInfo = (checkInId) => {
  const checkIn = checkIns.value.find(c => c.checkInId === checkInId);
  if (!checkIn) return `入住${checkInId}`;
  const customer = customers.value.find(c => c.customerId === checkIn.customerId);
  const room = rooms.value.find(r => r.roomId === checkIn.roomId);
  return `${customer ? customer.fullName : '未知客户'} - ${room ? room.roomNumber : '未知房间'}`;
};

const getCustomerName = (customerId) => {
  const customer = customers.value.find(c => c.customerId === customerId);
  return customer ? customer.fullName : `客户${customerId}`;
};

const getRoomNumber = (roomId) => {
  const room = rooms.value.find(r => r.roomId === roomId);
  return room ? room.roomNumber : `房间${roomId}`;
};

const formatDate = (dateStr) => {
  if (!dateStr) return '';
  return new Date(dateStr).toLocaleString();
};

const activeCheckIns = computed(() => {
  return checkIns.value.filter(checkIn => checkIn.status === 'active');
});

const openAdd = () => {
  dialogTitle.value = '新增结算';
  form.value = { 
    settlementId: null, 
    checkInId: '', 
    userId: 1, 
    checkInDays: '', 
    roomFee: '', 
    consumptionFee: 0, 
    discount: 0, 
    totalFee: '', 
    deposit: '', 
    refundAmount: '', 
    paymentMethod: '', 
    settlementDate: '', 
    notes: '' 
  };
  dialogVisible.value = true;
};

const openEdit = (row) => {
  dialogTitle.value = '编辑结算';
  form.value = { ...row };
  dialogVisible.value = true;
};

const onSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    if (!form.value.settlementId) {
      await addSettlement(form.value);
      ElMessage.success('新增成功');
    } else {
      await updateSettlement(form.value);
      ElMessage.success('修改成功');
    }
    dialogVisible.value = false;
    loadSettlements();
  });
};

const onDelete = (id) => {
  ElMessageBox.confirm('确定要删除该结算记录吗？', '提示', { type: 'warning' })
    .then(async () => {
      await deleteSettlement(id);
      ElMessage.success('删除成功');
      loadSettlements();
    });
};

onMounted(() => {
  loadSettlements();
  loadCheckIns();
  loadCustomers();
  loadRooms();
});
</script> 